
// 导入express框架
const express = require('express')
const cors = require('cors')
const token = require('./api/token')
const app = express()
const fs = require("fs")
const path = require('path')

app.use(express.static(path.join(__dirname, 'upload')))
app.get('/node/staticFile/:name', (req, res) => { // 读取静态文件
  try {
    fs.statSync(path.join(__dirname, `upload/${req.params.name}`))
    res.sendFile(path.join(__dirname, `upload/${req.params.name}`))
  } catch (error) {
    res.send({ code: 404, msg: `${req.params.name}暂无资源` })
  }
})

const corsOptions = {
  origin: 'http://192.168.5.36:9528',
  credentials: true,
  maxAge: '1728000'
  // 这一项是为了跨域专门设置的
}
// 跨域和json中间件
app.use(cors(corsOptions))

// // 设置允许跨域请求
app.all('*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', req.headers.origin) // 访问控制允许来源：所有
  res.header('Access-Control-Allow-Credentials', true) // 请求头里带上cookie,必须是你的源地址
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept') // 访问控制允许报头 X-Requested-With: xhr请求
  res.header('Access-Control-Allow-Metheds', 'PUT, POST, GET, DELETE, OPTIONS') // 访问控制允许方法
  res.header('X-Powered-By', 'nodejs') // 自定义头信息，表示服务端用nodejs
  res.header('Content-Type', 'application/json;charset=utf-8')
  if (req.url.substring(24, 15) === 'login' || req.url.substring(24, 15) === 'Test/page') {
    next()
  } else {
    const key = req.headers.token
    token.verifyToken(key).then(() => {
      next()
    }).catch(() => {
      res.send({ code: 403, msg: '登录已过期,请重新登录' })
    })
  }
})

require('./db')(app)
require('./api/user')(app)
require('./api/robot')(app)
require('./api/table')(app)
require('./api/file')(app)
require('./api/log')(app)
require('./api/socket')(app)

app.listen(9527, () => {
  console.log('http://localhost:9527')
})
